package br.ufpe.cin.mouse.pizza.webservice;

import java.util.Iterator;

import javax.xml.bind.JAXB;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SAAJResult;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.dom.DOMSource;

import br.ufpe.cin.mouse.pizza.webservice.jaxws.ObtemIdUltimoPedido;

public class PedidoSOAPHandler {

	private static final String NAMESPACE_URI = "http://webservice.pizza.mouse.cin.ufpe.br/";
	private static final QName OBTEM_ID_ULTIMO_PEDIDO = new QName(NAMESPACE_URI, "obtemIdUltimoPedido");

	private MessageFactory messageFactory;
	private PedidoAdapter pedidoAdapter;

	public PedidoSOAPHandler() throws SOAPException {
		
		messageFactory = MessageFactory.newInstance();
		pedidoAdapter = new PedidoAdapter();
		
	}

	public SOAPMessage handleSOAPRequest(SOAPMessage request) throws SOAPException {
		
		SOAPBody soapBody = request.getSOAPBody();
		Iterator iterator = soapBody.getChildElements();
		Object responsePojo = null;
		
		while (iterator.hasNext()) {
			
			Object next = iterator.next();
			
			
			if (next instanceof SOAPElement) {
				SOAPElement soapElement = (SOAPElement) next;
				QName qname = soapElement.getElementQName();
				
				if (OBTEM_ID_ULTIMO_PEDIDO.equals(qname)) {
					
					responsePojo = handleObtemIdUltimoPedidoRequest(soapElement);
					break;
				}
				
			}
			
		}
		
		SOAPMessage soapResponse = messageFactory.createMessage();
		soapBody = soapResponse.getSOAPBody();
		
		if (responsePojo != null) {
			
			JAXB.marshal(responsePojo, new SAAJResult(soapBody));
			
		} else {
			
			SOAPFault fault = soapBody.addFault();
			fault.setFaultString("Unrecognized SOAP request.");
			
		}
		
		return soapResponse;
		
	}

	private Object handleObtemIdUltimoPedidoRequest(SOAPElement soapElement) {
		
		ObtemIdUltimoPedido obtemIdUltimoPedidoRequest = JAXB.unmarshal(new DOMSource(soapElement), ObtemIdUltimoPedido.class);
		return pedidoAdapter.obtemIdUltimoPedido(obtemIdUltimoPedidoRequest);
		
	}

}
